const app = getApp(); // 获取全局app实例

// 辅助函数：格式化日期时间
function formatDateTime(timestamp) {
  if (!timestamp) return '-';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

Page({
  data: {
    serverUrl: app.globalData.baseUrl, // 使用全局配置的baseUrl
    userInfo: {
      id: '',
      avatar: '',
      username: '',
      email: '',
      phone: '',
      created_at: '',
      last_login: '',
      active: true
    },
    passwordInput: '******',
    showPasswordModal: false,
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },
  onLoad() {
    // onShow 会处理数据加载
  },
  onShow() {
    this.loadUserInfo();
  },
  loadUserInfo() {
    const userId = wx.getStorageSync('userId'); // 假设用户ID存储在本地缓存中
    if (!userId) {
      wx.showToast({ title: '用户ID未找到，请先登录', icon: 'none' });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }

    wx.showLoading({ title: '加载中...' });
    wx.request({
      url: `${this.data.serverUrl}/api/users/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}` // 假设 token 存储在本地缓存中
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200 && res.data) {
          const fetchedUser = res.data;
          let avatarUrl = fetchedUser.avatar_url;
          if (avatarUrl && !avatarUrl.startsWith('http')) {
            avatarUrl = `${this.data.serverUrl}${avatarUrl}`;
          }

          this.setData({
            userInfo: {
              id: fetchedUser.id || '',
              avatar: avatarUrl || '../../assets/images/default-avatar.png',
              username: fetchedUser.username || '未设置用户名',
              email: fetchedUser.email || '未绑定',
              phone: fetchedUser.phone || '',
              created_at: formatDateTime(fetchedUser.created_at),
              last_login: formatDateTime(fetchedUser.last_login),
              active: fetchedUser.active // 假设后端发送布尔值或等效值
            },
            passwordInput: '******' // 密码默认显示为星号
          });
          wx.setStorageSync('userInfo', this.data.userInfo); // 更新本地缓存为最新数据
        } else {
          wx.showToast({ title: res.data.message || '获取用户信息失败', icon: 'none' });
          console.error('获取用户信息失败', res);
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误，获取用户信息失败', icon: 'none' });
        console.error('获取用户信息失败', err);
      }
    });
  },
  onInput(e) {
    const field = e.currentTarget.dataset.field;
    if (field === 'password') {
      this.setData({ passwordInput: e.detail.value });
    } else {
      this.setData({
        [`userInfo.${field}`]: e.detail.value
      });
    }
  },
  onChangeAvatar() {
    const userId = this.data.userInfo.id || wx.getStorageSync('userId');
    wx.chooseImage({
      count: 1,
      success: res => {
        wx.uploadFile({
          url: `${this.data.serverUrl}/api/users/${userId}/avatar`,
          filePath: res.tempFilePaths[0],
          name: 'avatar',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: (uploadRes) => {
            const data = JSON.parse(uploadRes.data);
            let avatarUrl = data.avatarUrl;
            if (avatarUrl && !avatarUrl.startsWith('http')) {
              avatarUrl = `${this.data.serverUrl}${avatarUrl}`;
            }
            if (data.success) {
              this.setData({ 'userInfo.avatar': avatarUrl });
              wx.showToast({ title: '头像已更新', icon: 'success' });
              this.loadUserInfo(); // 头像更新成功后刷新用户信息
            } else {
              wx.showToast({ title: data.message || '上传失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '上传失败', icon: 'none' });
          }
        });
      }
    });
  },
  onChangePassword() {
    this.setData({
      showPasswordModal: true,
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
  },
  onPasswordInput(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({ [field]: e.detail.value });
  },
  onPasswordModalConfirm() {
    const { oldPassword, newPassword, confirmPassword, userInfo, serverUrl } = this.data;
    if (!oldPassword || !newPassword || !confirmPassword) {
      wx.showToast({ title: '请填写完整', icon: 'none' });
      return;
    }
    if (newPassword !== confirmPassword) {
      wx.showToast({ title: '两次新密码不一致', icon: 'none' });
      return;
    }
    wx.request({
      url: `${serverUrl}/api/users/${userInfo.id}/password`,
      method: 'POST',
      data: {
        currentPassword: oldPassword,
        newPassword
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          wx.showToast({ title: '修改成功', icon: 'success' });
          this.setData({ showPasswordModal: false });
        } else {
          wx.showToast({ title: res.data.message || '修改失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  onPasswordModalCancel() {
    this.setData({ showPasswordModal: false });
  },
  onSubmit() {
    const { userInfo } = this.data;
    const userId = userInfo.id || wx.getStorageSync('userId');

    // 准备要发送到后端的数据 - 只包含可更新的字段
    const updateData = {
      username: userInfo.username,
      email: userInfo.email,
      phone: userInfo.phone
    };

    wx.request({
      url: `${this.data.serverUrl}/api/users/${userId}`,
      method: 'PUT',
      data: updateData,
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          wx.showToast({ title: '保存成功', icon: 'success' });
          this.loadUserInfo(); // 保存成功后刷新用户信息
        } else {
          wx.showToast({ title: res.data.message || '保存失败', icon: 'none' });
          console.error('保存用户信息失败', res);
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        console.error('保存用户信息失败', err);
      }
    });
  },
  onLogout() {
    wx.clearStorageSync();
    wx.showToast({ title: '已退出登录', icon: 'success' });
    wx.switchTab({ url: '/pages/mine/mine' });
  },
  onSwitchAccount() {
    wx.clearStorageSync();
    wx.navigateTo({ url: '/pages/login/login' });
  }
}); 